package server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import communication.message.Player;

import exception.BadArgumentValueException;

public class Championship implements Runnable {
	GamePool gamePool;
	HashMap<String, ClientServiceHandle> clientThreads;
	
	public Championship(GamePool gamePool, HashMap<String, ClientServiceHandle> clientThreads) {
		this.gamePool = gamePool;
		this.clientThreads = clientThreads;
	}
	
	public void run() {
		Set<String> waitingPlayers = gamePool.getWaitingPlayers();
		String[] players = new String[waitingPlayers.size()];
		int[] wins = new int[waitingPlayers.size()];
		int i = 0;
		for(String nick : waitingPlayers) 
			players[i++] = nick;
			
		for(i = 0; i < players.length; ++i) {
			for(int j = i+1; j < players.length; ++j) {
				try {
					String[] playPlayers = new String[2];
					playPlayers[0] = players[i];
					playPlayers[1] = players[j];
					gamePool.startPlay(playPlayers);
					clientThreads.get(playPlayers[0]).getThread().join();
					clientThreads.get(playPlayers[1]).getThread().join();
					if(clientThreads.get(players[i]).getClientService().getWinner() > 0)
						++wins[j];
					else
						++wins[i];
					//jakoś poczkej na koniec tej rozgrywki
					clientThreads.get(playPlayers[0]).setThread(new Thread(clientThreads.get(playPlayers[0]).getClientService()));
					clientThreads.get(playPlayers[1]).setThread(new Thread(clientThreads.get(playPlayers[1]).getClientService()));
					gamePool.addClient(clientThreads.get(playPlayers[0]).getClientService().getClientHandle());
					gamePool.addClient(clientThreads.get(playPlayers[1]).getClientService().getClientHandle());
					clientThreads.get(playPlayers[0]).getThread().start();
					clientThreads.get(playPlayers[1]).getThread().start();
				} catch (BadArgumentValueException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		ArrayList<Player> championlist = new ArrayList<Player>();
		for(int j = 0; j < players.length; ++j) {
			try {
				championlist.add(new Player(players[j], wins[j], players.length - wins[j] - 1));
			} catch (BadArgumentValueException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		for(i = 0; i < players.length; ++i) {
			try {
				clientThreads.get(players[i]).getClientService().sendChampionList(championlist);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
